package jpa4azure.type;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;

import com.windowsazure.samples.Property;
import com.windowsazure.samples.PropertyCollection;

class EmbeddedContext extends FieldContext {

	public EmbeddedContext(Object o, Field field) {
		super(o, field);
	}

	public Object value() {
		Object result = null;
		try {
			//field.setAccessible(true);
			result = field.get(subject);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream os = new ObjectOutputStream(bos);
			os.writeObject(result);
			return ByteBuffer.wrap(bos.toByteArray());
		} catch (Exception e) {
			Utils.runtime(e);
		}
		return result;
	}

	public void setProperty(Object v) {
		try {
			ByteBuffer buffer = (ByteBuffer) v;
			byte[] b = buffer.array();
			ByteArrayInputStream bis = new ByteArrayInputStream(b);
			ObjectInputStream os = new ObjectInputStream(bis);
			Object o = os.readObject();
			//field.setAccessible(true);
			field.set(subject, o);
		} catch (Exception e) {
			Utils.runtime(e);
		}
	}

	public void getCloudTableColumn(PropertyCollection values) throws Exception {
		if (value() == null)
			return;
		values.add(Property.newProperty(getFieldname(), (ByteBuffer)value() ));
	}

}